package com.example.animationdrawabledemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;


/**
 * Created by Administrator on 2018/6/20.
 */

public class ImageViewCustom  extends android.support.v7.widget.AppCompatImageView {

    private int row;
    private int col;
    private int offsetX;
    private int offsetY;



    public ImageViewCustom(Context context) {
        this(context,null);
    }

    public ImageViewCustom(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ImageViewCustom(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    postInvalidate();
                }

            }
        }).start();
    }

    int count=0;
    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        Drawable drawable=getDrawable();
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        Bitmap bitmap = bitmapDrawable.getBitmap();
        int imageWidth=drawable.getIntrinsicWidth()/col;
        int imageHeight=drawable.getIntrinsicHeight()/row;
        float scaleX=(float) getWidth()/imageWidth;
        float scaleY=(float)getHeight()/imageHeight;
        if(count==row*col){
            count=0;
        }
        int startX = (count%col)*imageWidth;
        int startY = (count/col)*imageHeight;
        canvas.save();
        canvas.scale(scaleX,scaleY);
        canvas.drawBitmap(bitmap,-startX+offsetX,-startY+offsetY,new Paint());
        canvas.restore();
        count++;
    }

    public void setSection(int row,int col,int offsetX,int offsetY){
        this.row = row;
        this.col = col;
        this.offsetX = offsetX;
        this.offsetY = offsetY;
    }
}
